<template>
  <div class="checkbox-wrapper" :class="{ disabled: disabled }" @click="handleClick" role="group">
    <div
      class="checkbox-container"
      role="checkbox"
      :aria-checked="checked"
      :aria-labelledby="label ? 'checkbox-label' : undefined">
      <!-- 未选中状态图标 -->
      <svg
        v-if="!checked"
        width="20"
        height="20"
        viewBox="0 0 20 20"
        fill="none"
        xmlns="http://www.w3.org/2000/svg">
        <rect x="2" y="2" width="16" height="16" rx="2" fill="#F4F5F7" stroke="#CBCBCB" />
      </svg>

      <!-- 选中状态图标 -->
      <svg
        v-else
        width="20"
        height="20"
        viewBox="0 0 20 20"
        fill="none"
        xmlns="http://www.w3.org/2000/svg">
        <rect x="2" y="2" width="16" height="16" rx="2" fill="#52C41A" stroke="#52C41A" />
        <path
          d="M5 10L8 13L15 6"
          stroke="white"
          stroke-width="1.5"
          stroke-linecap="round"
          stroke-linejoin="round" />
      </svg>
    </div>

    <!-- 显示标签文本 -->
    <span v-if="label" class="checkbox-label" id="checkbox-label">
      {{ label }}
    </span>
  </div>
</template>

<script setup lang="ts">
  import { ref, watch } from 'vue';

  // 定义组件的Props
  const props = defineProps<{
    // 初始选中状态
    modelValue?: boolean;
    // 是否禁用
    disabled?: boolean;
    // 显示的标签文本
    label?: string;
  }>();

  // 定义组件可以发出的事件
  const emit = defineEmits<{
    // Vue3 的 v-model 事件
    (e: 'update:modelValue', value: boolean): void;
    // 点击事件
    (e: 'change', value: boolean): void;
  }>();

  // 内部状态
  const checked = ref(false);

  // 监听外部的modelValue变化，同步到内部状态
  watch(
    () => props.modelValue,
    (newValue) => {
      if (newValue !== undefined) {
        checked.value = newValue;
      }
    },
    { immediate: true }
  );

  // 处理点击事件
  const handleClick = () => {
    // 如果禁用，则不响应点击
    if (props.disabled) return;

    // 切换选中状态
    checked.value = !checked.value;

    // 发出事件通知父组件
    emit('update:modelValue', checked.value);
    emit('change', checked.value);
  };
</script>

<style scoped>
  .checkbox-wrapper {
    display: inline-flex;
    align-items: center;
    cursor: pointer;
    user-select: none;
    transition: opacity 0.2s;
  }

  .checkbox-wrapper.disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }

  .checkbox-container {
    display: inline-flex;
    align-items: center;
    justify-content: center;
  }

  .checkbox-label {
    margin-left: 8px;
    font-size: 14px;
    color: #333;
    line-height: 1;
  }
</style>
